import request from '@/router/axios';
const GEN_DATA_KEY = 'GEN_DATA_KEY'
/**
 * 通过表名称获取元数据
 * @param {*} data 
 * @returns 
 */
export const getModelTable = (data) => request({
  url: '/molegen/getModelTable',
  method: 'get',
  params: data
});
/**
 * 保存元数据
 * @param {*} data 
 */
export const save = (data) => {
  if(data.table.columns) {
    data.table.columns.forEach(item=>{
      Object.keys(item).forEach(key=>{
        if(key.startsWith("$")) {
          delete item[key]
        }
      })
    })
  }
  window.localStorage.setItem(GEN_DATA_KEY,JSON.stringify(data,null,2))
}
/**
 * 保存行
 * @param {*} data 
 */
 export const saveRow = (row) => {
  let data = get()
  if(!data.table.columns) {
    data.table.columns = []
  } 
  var index = -1;
  for(let i=0,len=data.table.columns.length;i<len;i++) {
    if(row.javaProperty == data.table.columns[i].javaProperty) {
      index = i;
      break;
    } 
  }
  if(index !== -1) {
    data.table.columns[index] = row
  } else {
    data.table.columns.push(row)
  }
  save(data)
}
/**
 * 更新行
 * @param {*} row
 * @param {*}  index
 */
 export const updateRow = (row,index) => {
  let data = get()
  if(data.table.columns) {
    data.table.columns[index] = row
    save(data)
  } 
}
/**
 * 获取元数据
 * @returns 
 */
export const get = () => {
  let data = window.localStorage.getItem(GEN_DATA_KEY)
  if(data) {
    return JSON.parse(data)
  } else {
    return {
      table: {}
    }
  }
}
/**
 * 删除行
 * @param {*} row 
 * @returns 
 */
export const remove = (row) => {
  let data = get()
  if(data.table.columns) {
    data.table.columns.splice(row.$index,1)
    save(data)
    return row.$index
  }
  return -1;
}
/**
 * 清空数据
 */
export const clearData = () => {
  window.localStorage.removeItem(GEN_DATA_KEY)
}
/**
 * 保存基本信息
 * @param {*} form 
 */
 export const saveBaseInfo = (form) => {
  let data = get()
  data.moduleName = form.moduleName
  data.table.tableName = form.tableName
  data.table.tableCameName = toHump(form.tableName)
  data.table.className = data.table.tableCameName[0].toUpperCase()+data.table.tableCameName.substring(1)
  data.table.remark = form.remark
  data.table.layoutType = form.layoutType
  save(data)
}
/**
 * 下划线转驼峰
 * @param {*} name 
 * @returns 
 */
export const toHump = (name) => {
  // eslint-disable-next-line no-useless-escape
  return name.replace(/\_(\w)/g, function(all, letter){
    return letter.toUpperCase();
  });
}